package com.itcoon.cloud.framework.springdoc.plugin;/**
 * @author Athric Yu
 * 2024/11/12
 **/

import com.fasterxml.jackson.databind.type.SimpleType;
import com.itcoon.cloud.framework.config.TemporalPatternConfig;
import com.itcoon.cloud.framework.properties.TemporalPatternConfigProperties;
import com.itcoon.cloud.framework.temporal.AbstractConverter;
import com.itcoon.cloud.framework.utils.TemporalConvertUtils;
import io.swagger.v3.core.converter.AnnotatedType;
import io.swagger.v3.oas.models.media.Schema;
import org.springdoc.core.customizers.PropertyCustomizer;

import java.lang.reflect.Type;
import java.time.temporal.Temporal;

/**
 *
 *
 * @author Athric Yu
 * 2024/11/12
 **/
public class TemporalPropertyCustomizer implements PropertyCustomizer, TemporalCustomizer {

    private final TemporalPatternConfigProperties temporalPatternConfigProperties;

    public TemporalPropertyCustomizer(TemporalPatternConfigProperties temporalPatternConfigProperties) {
        this.temporalPatternConfigProperties = temporalPatternConfigProperties;
    }

    @Override
    public Schema customize(Schema property, AnnotatedType type) {
        Type type_ = type.getType();
        if(type_ instanceof SimpleType){
            SimpleType fieldType = (SimpleType)type.getType();
            // 获取字段class
            Class<?> fieldClazz = fieldType.getRawClass();
            if(Temporal.class.isAssignableFrom(fieldClazz)){
                TemporalPatternConfigProperties.TemporalSerialization  temporalSerialization= TemporalConvertUtils.getTemporalSerialization((Class<? extends Temporal>) fieldClazz);
                Schema schema = getSchema(temporalSerialization.getSerialType(), property);
                Temporal temporal = TemporalConvertUtils.getInstance((Class<? extends Temporal>) fieldClazz);
                AbstractConverter<?, Temporal> abstractConverter = TemporalPatternConfig.getConverter(temporalSerialization.getSerialType(), fieldClazz);
                Object example = abstractConverter.format(temporal);
                schema.setExample(example);
                return schema;
            }
        }
        return property;
    }
}
